<template>
  <div ref="OrganDiagram" class="_wz_cent_main _wz_OrganDiagram">
    <Card dis-hover :bordered="true" style="margin:0 0 10px;">
      <p slot="title">搜索</p>
      <Form ref="formSearch" :model="formDataSearch" label-position="right" :label-width="120" inline>
        <FormItem label="运输企业">
          <i-select v-model="formDataSearch.deptUuid" filterable placeholder="请选择运输企业" clearable>
            <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
          </i-select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="searchSubmit">搜索</Button>
        </FormItem>
      </Form>
    </Card>
    <Card dis-hover :bordered="true">
      <p slot="title">{{dataType == 1?'企业组织架构':dataType == 2?'应急领导小组':'安全生产委员会'}}</p>
      <div slot="extra">
        <!--组织架构-->
        <div v-if="dataType==1">
          <Button type="primary" @click="addData">添加</Button>
          <Button type="warning" @click="modifyData">修改</Button>
          <Button type="error" @click="remData">删除</Button>
        </div>
        <!--领导小组-->
        <div v-if="dataType==2">
          <Button type="primary" @click="addData">添加</Button>
          <Button type="warning" @click="modifyData">修改</Button>
          <Button type="error" @click="remData">删除</Button>
        </div>
        <!--生产委员会-->
        <div v-if="dataType==3">
          <Button type="primary" @click="addData">添加</Button>
          <Button type="warning" @click="modifyData">修改</Button>
          <Button type="error" @click="remData">删除</Button>
        </div>
      </div>
      <div id="container" style="width: 100%;height: 500px;"></div>
    </Card>

    <Modal :title="formTitle" v-model="formOperation" :mask-closable="false" :footer-hide="true">
      <OrganDiagramAdd v-if="formOperation" @closeFun="closeFun" :selectData="oldData" :deptData="formDataSearch" :formType="formType" :dataType="dataType"></OrganDiagramAdd>
    </Modal>

    <Spin size="large" fix v-if="spinShow"></Spin>

  </div>
</template>
<script>


  import OrganDiagramAdd from "./OrganDiagramAdd.vue";

  export default {
    components: {
      OrganDiagramAdd,//挂车添加
    },
    props: ["dataType"],//接收来自父组件的数据
    data() {
      return {
        showDataList:[],
        spinShow:false,//本页加载

        subDeptList: [],//运输企业

        formDataSearch: {},
        formTitle: '',
        formOperation: false,
        formType: '',
        oldData: null,

        graph: null
      }
    },
    beforeCreate() {//beforeCreate创建前状态

    },
    created() {//created创建完毕状态

    },
    beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

    },
    mounted() {//mounted 挂载结束状态
      var that = this;

      //运输企业
      that.axios.post(that.apiUrl.coreDeptCoreDeptList,{}).then(res => {
        if (!!res) {
          that.subDeptList = res.data.data;
          that.$set(that.formDataSearch, 'deptUuid', that.subDeptList[0].uuid)
          that.$nextTick(function () {
            that.diagramalData()
          })
        }
      }).catch(err => {
        console.log("失败", err)
      })


    },
    methods: {//执行的方法
      searchSubmit() {//搜索
        this.diagramalData();
      },
      diagramalData() {
        var that = this;
        that.formDataSearch.organizationType = that.dataType;
        that.axios.post(that.apiUrl.webApi + "/safety/organization/organizationList",  that.formDataSearch).then(res => {
          if (!!res) {
            if (res.data.data.length == 0) {
              that.oldData = null;
              if (!!that.graph) {
                that.graph.destroy();
                that.graph = null;
              }
              return false;
            }
            that.showDataList = JSON.parse(JSON.stringify(res.data.data));
            res.data.data.forEach(function (k, i) {
              k.label = k.organizationPosition;
              k.description = k.organizationName;
            })
            let treeAttr = {
              id: 'id',
              parendId: 'parentOrganizationId',
              name: 'organizationPosition',
              rootId: null
            };
            var dataList = that.public.toTreeData(res.data.data, treeAttr);//父子同级数据 处理成树形数据
            that.charLoad(dataList[0])
          }
        }).catch(err => {
          console.log("失败", err)
        })

      },
      charLoad(data) {
        var that = this;
        that.oldData = null;
        const width = document.getElementById('container').scrollWidth - 20;
        const height = document.getElementById('container').scrollHeight - 20;
        if (!!that.graph) {
          that.graph.destroy();
          that.graph = null;
        }
        that.graph = new that.G6.TreeGraph({
          container: 'container',
          width,
          height,
          linkCenter: true,
          // renderer: 'svg',
          modes: {
            default: ['drag-canvas', 'zoom-canvas',], //拖拽 缩放
          },
          defaultNode: {//容器
            type: 'modelRect',
            size: [150, 80],
            style: {
              radius: 5,
              stroke: '#69c0ff',
              fill: '#ffffff',
              lineWidth: 1,
              fillOpacity: 1,
            },
            // 文本样式配置
            labelCfg: {
              style: {
                fill: '#595959',
                fontSize: 14,
              },
              offset: 30,
            },
            // 左侧的小矩形
            preRect: {
              show: true,
              width: 4,
              fill: '#40a9ff',
              radius: 2,
            },
            // 节点中icon配置
            logoIcon: {
              // 是否显示icon，值为 false 则不渲染icon
              show: true,
              x: 0,
              y: 0,
              // icon的地址，字符串类型
              img: 'https://gw.alipayobjects.com/zos/basement_prod/4f81893c-1806-4de4-aff3-9a6b266bc8a2.svg',
              width: 16,
              height: 16,
              // 用于调整图标的左右位置
              offset: 0,
            },
            // 节点中表示状态的icon配置
            stateIcon: {
              show: false,
            },
          },
          defaultEdge: {//边框
            type: 'cubic-vertical',//cubic-horizontal //polyline   //quadratic
            style: {
              endArrow: true,//箭头
              stroke: '#000',
            },
          },
          layout: {//布局
            type: 'compactBox',
            direction: 'TB',//'TB',//'LR',
            width: width,
            height: height,
            getId: function getId(d) {
              return d.id;
            },
            getWidth: function getWidth() {//左右边距
              return -30;
            },
            getHeight: function getHeight() {//上下边距
              return 100;
            },
            getVGap: function getVGap() {
              return 0;
            },
            getHGap: function getHGap() {
              return 100;
            },
          },
          nodeStateStyles: {
            click: {
              lineWidth: 2,
              stroke: '#1890ff',
              fill: '#e6f7ff',
            },
          },
        });

        that.graph.node(function (node) {
          return {
            label: node.label,
            labelCfg: {
              offset: 30,
              position: node.children && node.children.length > 0 ? 'left' : 'right',
            },
          };
        });
        that.graph.data(data);
        that.graph.render();
        that.graph.fitView();

        // 点击时选中，再点击时取消
        that.graph.on('node:click', ev => {
          const {item} = ev;
          if (!!that.oldData) {
            that.graph.setItemState(that.oldData, 'click', false);
          }
          that.oldData = item;
          that.graph.setItemState(item, 'click', true);
          // const node = ev.item;
          // graph.setItemState(node, 'selected', !node.hasState('selected')); // 切换选中
        });
      },
      //添加
      addData() {
        var that = this;
        if(that.showDataList.length == 0){
          that.formTitle = '添加';
          that.formType = 'add';
          that.formOperation = true;
        }else{
          if(!!that.oldData){
            that.formTitle = '添加';
            that.formType = 'add';
            that.formOperation = true;
          }else{
            that.$Message.error('只可以添加一个顶级');
          }
        }

      },
      //修改
      modifyData() {
        var that = this;
        if (!!that.oldData) {
          that.formTitle = '修改';
          that.formType = 'modify';
          that.formOperation = true;
        } else {
          that.$Message.error('请点击需要修改的组织');
        }
      },
      //删除
      remData() {
        var that = this;
        if (!!that.oldData) {
          that.$Modal.confirm({
            title: '删除提醒',
            content: '确定要删除选中的记录？',
            onOk: () => {
              that.spinShow = true;
              that.axios.post(that.apiUrl.webApi + "/safety/organization/organizationDelete",{uuid:that.oldData._cfg.model.uuid}).then(res => {
                that.spinShow = false;
                if (!!res) {
                  that.$Message.success('删除成功');
                  that.diagramalData();
                }
              }).catch(err => {
                console.log("失败", err)
              })
            },
            onCancel: () => {
              //点击取消
            }
          });
        } else {
          that.$Message.error('请点击需要删除的组织');
        }
      },
      //添加修改触发后关闭刷新
      closeFun(data) {
        var that = this;
        if (data) {//添加修改 刷新表单
          that.diagramalData();
        }
        that.formOperation = false;

      },

    },
    watch: {//监听

    },
    beforeUpdate() {//beforeUpdate 更新前状态

    },
    updated() {//updated 更新完成状态

    },
    beforeDestroy() {//beforeDestroy 销毁前状态

    },
    destroyed() {//destroyed 销毁完成状态

    }
  }
</script>
<style lang="less">
  ._wz_OrganDiagram {
    display: flex;
    flex-direction: column;


    .ivu-card-body {
      height: calc(100% - 51px);
      canvas, svg {
        display: block;
      }
    }

    /*._wz_OrganDiagram_cent {*/
    /*  height: calc(100% - 142px - 10px);*/

    /*  .ivu-card-bordered {*/
    /*    height: 100%;*/
    /*  }*/

    /*  .ivu-card-body {*/
    /*    height: calc(100% - 51px);*/
    /*  }*/

    /*  */
    /*}*/
  }
</style>
